package com.ahcloud.enhance.curator.lock;

import com.ahcloud.enhance.lock.base.ILock;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;

/**
 * @program: distributedlock-enhance
 * @description:
 * @author: YuKai Fan
 * @create: 2024/4/30 20:18
 **/
public class ZkLock implements ILock<CuratorFramework> {

    private final CuratorFramework client;

    public ZkLock(CuratorFramework client) {
        this.client = client;
    }

    private InterProcessMutex getMutexLock(String path) {
        return new InterProcessMutex(getClient(), path);
    }

    @Override
    public void lock(String lockKey) throws Exception {
        getMutexLock(lockKey).acquire();
    }

    @Override
    public void unlock(String lockKey) throws Exception {
        getMutexLock(lockKey).release();
    }

    @Override
    public void lock(String lockKey, int timeout) throws Exception {
        getMutexLock(lockKey).acquire(timeout, TimeUnit.MILLISECONDS);
    }

    @Override
    public void lock(String lockKey, long timeout, TimeUnit unit) throws Exception {
        getMutexLock(lockKey).acquire(timeout, unit);
    }

    @Override
    public boolean tryLock(String lockKey) throws Exception {
        return tryLock(lockKey, 3, TimeUnit.SECONDS);
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime, TimeUnit unit) throws Exception {
        return getMutexLock(lockKey).acquire(waitTime, unit);
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) throws Exception {
        return getMutexLock(lockKey).acquire(waitTime, unit);
    }

    @Override
    public boolean isLocked(String lockKey) {
        return getMutexLock(lockKey).isAcquiredInThisProcess();
    }

    @Override
    public CuratorFramework getClient() {
        return client;
    }
}
